const schedule = require('node-schedule')
const jsonfile = require('jsonfile')
const path = require('path')
const mottoDB = require('../db/motto')

let mottoList = []
let todayMotto = null

//定时器任务
/*  
  通配符解释
  * * * * * *
  ┬ ┬ ┬ ┬ ┬ ┬
  │ │ │ │ │  |
  │ │ │ │ │ └ day of week (0 - 7) (0 or 7 is Sun)
  │ │ │ │ └───── month (1 - 12)
  │ │ │ └────────── day of month (1 - 31)
  │ │ └─────────────── hour (0 - 23)
  │ └──────────────────── minute (0 - 59)
  └───────────────────────── second (0 - 59, OPTIONAL)
  */
let task = () => {  
  schedule.scheduleJob('0 0 0 * * *', () => { 
    if(mottoList.length === 0){
      init()
    }else{
      todayMotto = mottoList.splice(Math.random() * mottoList.length, 1)[0]
      // console.log("task")
      const mottoObj = {motto: todayMotto.motto, mottoRef: todayMotto.mottoRef}
      const file = path.join(__dirname, '../public/files/json/motto.json')
      jsonfile.writeFile(file, mottoObj)
    }
  })
}

let init = async () => {
  mottoList = await mottoDB.aggregate([{ $match: {status: 1}}])
  todayMotto = mottoList.splice(Math.random() * mottoList.length, 1)[0]
  
  // console.log('init');
  let mottoObj = null
  if(!todayMotto){
    mottoObj = {motto: '学而时习之，不亦说乎。', mottoRef: '论语·学而'}
  }else{
    mottoObj = {motto: todayMotto.motto, mottoRef: todayMotto.mottoRef}
  }
  
  const file = path.join(__dirname, '../public/files/json/motto.json')
  jsonfile.writeFile(file, mottoObj)
    
  //   .then(res => {
  //     // console.log('Write complete')
  //   })
  //   .catch(error => console.error(error))
}

init()
task()

module.exports = todayMotto